package spotor.client.provider;

import spotor.client.provider.SpotorContract.PlacesColumns;
import spotor.client.provider.SpotorContract.PlansColumns;
import spotor.client.provider.SpotorContract.StatesColumns;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;

public class SpotorDatabase extends SQLiteOpenHelper {
	private static final String TAG = "SpotorDatabase";
	
	private static final String DATABASE_NAME = "spotor.db";

	private static final int DATABASE_VERSION = 0;
	
	interface Tables
	{
		String PLACES = "places";
		String PLANS = "plans";
		String STATES = "states";
		String BLOGS = "blogs";
		String PHOTOS = "photos";
	}
	
	private interface Triggers{
		
	}
	
	public SpotorDatabase(Context context){
		super(context,DATABASE_NAME,null,DATABASE_VERSION);
	}
	
	public SpotorDatabase(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		db.execSQL("CREATE TABLE" + Tables.PLACES + "("
				+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+ PlacesColumns.PLACE_ID + " INTEGER NOT NULL,"
				+ PlacesColumns.PLACE_NAME + " TEXT NOT NULL,"
				+ PlacesColumns.LATITUDE + " REAL NOT NULL,"
				+ PlacesColumns.LONGITUDE+ " REAL NOT NULL)");
		
		// 创建Plans数据表
		db.execSQL("CREATE TABLE" + Tables.PLANS +"("
				+BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+PlansColumns.PLAN_ID + " INTEGER NOT NULL,"
				+PlansColumns.PLAN_TITLE + " TEXT NOT NULL,"
				+PlansColumns.PLAN_START_PLACE + " INTEGER NOT NULL,"
				+PlansColumns.PLAN_END_PLACE + " INTEGER NOT NULL,"
				+"UNIQUE ("+ PlansColumns.PLAN_ID + ") ON CONFLICT REPLACE)");
		
		//创建States数据库
		db.execSQL("CREATE TABLE" + Tables.STATES +"("
				+BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
				+StatesColumns.STATE_ID + " INTEGER NOT NULL,"
				+StatesColumns.STATE_CONTENT + " TEXT NOT NULL,"
				+StatesColumns.STATE_CREATE_TIME + " INTEGER NOT NULL)");
		
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		int version = oldVersion;

		Log.d(TAG, "更新数据库版本："+version);
		
		if(version != DATABASE_VERSION){
			Log.w(TAG, "Destroying old data during upgrade");
			
			db.execSQL("DROP TABLE IF EXISTS " + Tables.PLACES);
			db.execSQL("DROP TABLE IF EXISTS " + Tables.PLANS);
			db.execSQL("DROP TABLE IF EXISTS " + Tables.STATES);
			
			onCreate(db);
		}
	}

}
